package com.leyou.trade.web;

import com.leyou.trade.entity.Cart;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;


    /**
     * 合并购物车
     * @param carts 本地localStorage中存储的购物车数据
     */
    @PostMapping("/list")
    public ResponseEntity<Void> asnyCarts(@RequestBody List<Cart> carts) {
        cartService.asnyCarts(carts);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 根据id删除数据库中的购物车信息
     * @param skuId 商品skuid
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBySkuId(@PathVariable("id")Long skuId) {
        cartService.deleteBySkuId(skuId);
        return ResponseEntity.status(HttpStatus.RESET_CONTENT).build();
    }


    /**
     * 更新购物车商品数量
     * @param skuId 商品的skuid
     * @param num 加购的数量
     */
    @PutMapping
    public ResponseEntity<Void> updateNum(
            @RequestParam("id") Long skuId,
            @RequestParam("num") Integer num) {
        cartService.updateNum(skuId, num);
        return ResponseEntity.status(HttpStatus.RESET_CONTENT).build();
    }


    /**
     * 添加购物车
     * @param cart 添加购物车的商品信息
     */
    @PostMapping
    public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
        cartService.addCart(cart);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 查看购物车商品
     * @return 返回查询到的数据库中的数据
     */
    @GetMapping("/list")
    public ResponseEntity<List<Cart>> listCarts() {
        return ResponseEntity.ok(cartService.listCarts());
    }
}
